import { api, domain } from '~/ui-domain'
import Storage from '@/utils/storage'

export default {
  data() {
    return {
      // 图片上传API
      MixinUploadApi: `${process.env.API_BASE || api.buyer}/uploaders`,
      // buyer端access_token
      MixinAccessToken: {Authorization: Storage.getItem('access_token')},
      // 地区上传API
      MixinRegionApi: `${process.env.API_BASE || api.base}/regions/@id/children`,
      // 域名
      MixinDomain: domain,
      // API
      MixinApi: api
    }
  },
  computed: {
    /** 计算是否有forward */
    MixinForward() {
      let { forward } = this.$route.query
      return forward ? `?forward=${decodeURIComponent(forward)}` : ''
    },
    /** 站点信息 */
    site() {
      return this.$store.getters.site
    }
  },
  methods: {
    /** 滚动到顶部【动画】 */
    MixinScrollToTop(top) {
      // eslint-disable-next-line no-undef
      $('html,body').animate({ scrollTop: top || 0 }, 300)
    },
    /** 用得比较多，放到mixin里 */
    MixinRequired(message, trigger) {
      return { required: true, pattern: /^\S.*$/gi, message: message, trigger: trigger || 'blur' }
    },
    /** 返回上一页 */
    MixinRouterBack() {
      if (window.history.length <= 1) {
        location.href = '/'
      } else {
        window.history.back()
      }
    },
    /** 是否为微信浏览器 */
    MixinIsWeChatBrowser() {
      return /micromessenger/i.test(navigator.userAgent)
    },
    /** base64转Blob */
    MixinBase64toBlob(base64) {
      const byteString = atob(base64.split(',')[1])
      const mimeString = base64.split(',')[0].split(':')[1].split(';')[0]
      const ab = new ArrayBuffer(byteString.length)
      const ia = new Uint8Array(ab)
      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i)
      }
      return new Blob([ab], {type: mimeString})
    },
    /**
     * 打开IM
     * @constructor
     */
    MixinOpenIm(shop, params = {}) {
      if (process.env.IM) {
        let url = `/chat?shop_id=${shop.shop_id}`
        if (params.goods_id) url += `&goods_id=${params.goods_id}`
        window.open(url)
      } else {
        if (!shop.shop_qq) return this.$message.error('当前店铺没有配置客服联系方式！')
        window.open(`http://wpa.qq.com/msgrd?v=3&uin=${shop.shop_qq}&site=qq&menu=yes`)
      }
    },
    /**
     * 模拟睡眠
     * @param timer
     * @returns {Promise<unknown>}
     * @constructor
     */
    MixinMockSleep(timer) {
      return new Promise(resolve => {
        setTimeout(resolve, timer)
      })
    }
  }
}
